import qs from "qs";
import Cookie from 'js-cookie' //npm install js-cookie --save

const NUXT_ENV_LANGUAGE = process.env.NUXT_ENV_LANGUAGE ? process.env.NUXT_ENV_LANGUAGE : "zh"

export default function({store, $axios, redirect }) {
  console.log(`axios-language=${NUXT_ENV_LANGUAGE}`)
  $axios.defaults.retry = { retries: 3 };
  $axios.defaults.withCredentials = true;// 是否允许带cookie这些
  //开发模式下开启debug
  $axios.defaults.debug = process.env.NODE_ENV == "production" ? false : true;

  // 设置请求头
  $axios.defaults.timeout = 5000;
  $axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  //$axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
  $axios.defaults.baseURL = process.env.NODE_ENV == "production"
    ? "http://score.ufu.auan.cn"
    : "http://localhost:3000";


  //request统一处理操作
  $axios.onRequest(config => {
    // POST传参序列化
    if(config.method === 'post'){

      config.data.api_version = "9.9.9";
      config.data.platform = "web";
      config.data.language_id = "1";
      config.data.gameID = "1";

      config.data = qs.stringify(config.data, {
        allowDots: true //Option allowDots can be used to enable dot notation
      });
    }
    if(store.state.token){
      config.params = {
        'token': store.state.token,
        'axios': 'server',
      }
    }

    return config;
  },(error) => {
    console.log("参数错误！");
    return Promise.reject(error);
  });

  //response统一处理操作
  $axios.onResponse(response => {

    // code状态码200判断
    if(response.data.code != '200'){
      console.log(response.data.msg);
      return Promise.resolve(response.data);
    }

  },(error) => {
    console.log("网络异常");
    return Promise.reject(error);
  });

  $axios.onError(error => {
    console.log("请求错误");
    return Promise.reject(error);
  });
}
